/**
 * 促销规则新增／编辑命名空间
 */

var ruleEdit = {};
ruleEdit.operation = {};
ruleEdit.constrainGoodsTable = null;
ruleEdit.giftTable = null;

ruleEdit.ruleId = "";
ruleEdit.ruleData = {};
ruleEdit.btnType = "";

var ruleEditFlag = false;
var shopEditFlag = false;
var constrainGoodsEditFlag = false;

$(document).ready(function () {
    ruleEdit.ruleId = extractParam("ruleId");
    ruleEdit.copyRuleId = extractParam("copyRuleId");
    ruleEdit.btnType = extractParam("btnType");
    $('#ruleIframeWindow', window.top.document).find("#btnSave").show();
    // 加载项目店铺列表
    ruleEdit.initShopList();
    ruleEdit.initCompValue();
    ruleEdit.initCompEvent();

    $('a[data-toggle="tab"]').on('shown.bs.tab', function (e) {
        var tables = $.fn.dataTable.tables({
            visible: true,
            api: true
        });
        if (tables.length > 0) {

            $(tables).DataTable().columns.adjust();
        }
        $(tables).find("th.sorting_asc").removeClass("sorting_asc");
    });

    // 初始化校验
    $("#ruleForm").validate({
        debug: true,
        ignore: "",
        errorPlacement: function (error, element) {
            error.insertAfter(element);
        }
    });

    if (!!ruleEdit.ruleId || !!ruleEdit.copyRuleId) {
        var ruleId = ruleEdit.ruleId || ruleEdit.copyRuleId;
        ruleEdit.loadRuleData(ruleId);
    }
    if (ruleEdit.btnType == "viewRule") {
        console.log("test");
        $("#ruleForm .btn-default").attr("disabled", true);
        $("#ruleForm input").attr("disabled", true);
        $("#ruleForm button").attr("disabled", true);
        $("#myTabContent button").attr("disabled", true);
        $("#myTabContent input").attr("disabled", true);
        $('#ruleIframeWindow', window.top.document).find("#btnSave").hide();
    }
});

ruleEdit.loadRuleData = function (ruleId) {
    ruleEdit.ruleData = ruleEdit.operation.getRuleData(ruleId);
    if (ruleEdit.ruleData) {
        ruleEdit.initPageByRuleData(ruleEdit.ruleData);
    }
};

ruleEdit.initPageByRuleData = function (ruleData) {
    // 规则名称
    $("#ruleName").val(ruleData.ruleName);

    if (!!ruleEdit.ruleId) {
        $("#ruleId").val(ruleData.ruleId);
    }

    // 规则默认启用
    if (ruleData.isEnable === "y") {
        $("#chkIsEnable").iCheck("check");
    } else {
        $("#chkIsEnable").iCheck("uncheck");
    }

    // 设置ID是否可重复参加
    if (ruleData.isDuplicatedIdEnable === "y") {
        $("#chkIsDuplicatedIdEnable").iCheck("check");
    } else {
        $("#chkIsDuplicatedIdEnable").iCheck("uncheck");
    }

    // 设置付款时间/拍单时间
    $("#selectCountingDateType").selectpicker('val', ruleData.countingDateType);

    var momentObjStart = moment(ruleData.countingDateStart, 'YYYY-MM-DD HH:mm');
    var momentObjEnd = moment(ruleData.countingDateEnd, 'YYYY-MM-DD HH:mm');

    ruleEdit.setdaterange(momentObjStart, momentObjEnd);

    // 设置整天/每日
    $("#selectEachDaySet").selectpicker('val', ruleData.isEachdaySetEnable);

    // 设置开始日期和结束日期
    $("#txtEachDayTimeStart").val(ruleData.eachDayTimeStart);
    $("#txtEachDayTimeEnd").val(ruleData.eachDayTimeEnd);

    // 设置选中的店铺
    for (var i = 0, j = ruleData.shopList.length; i < j; i++) {
        $("#projectShopList").selectpicker('val', ruleData.shopList[i].relShopId);
    }

    // 初始化赠品列表
    ruleEdit.initGiftTable(ruleData.giftList);

    // 初始化限定商品列表

    if (ruleData.isConstrainGoodsEnable == "y") {
        ruleEdit.initConstrainGoodsTable(ruleData.constrainGoodsList);
    }
    // 初始化规则
    ruleEdit.initCaculateRule(ruleData.presentCaculateRule);
};

ruleEdit.initCaculateRule = function (caculateRuleString) {
    // 初始化计算规则
    var caculateRuleObj = $.parseJSON(caculateRuleString);

    // 设置组合商品参与的选中
    if (caculateRuleObj.isGroupEnvolve == 'y') {
        $("#chkIsGroupEnvolve").iCheck("check");
    } else {
        $("#chkIsGroupEnvolve").iCheck("uncheck");
    }

    $("input[value=\"" + caculateRuleObj.giftType + "\"].giftSendType").iCheck("check");

    if (caculateRuleObj.sendType == "buySend") {
        ruleEdit.initBuySendPage(caculateRuleObj);
    } else if (caculateRuleObj.sendType == "fullSend") {
        ruleEdit.initFullSendPage(caculateRuleObj);
    }
};

ruleEdit.initBuySendPage = function (ruleObj) {
    $("#buySend").iCheck("check");
    var segment = ruleObj.segments[0];
    $("#buyPurchaseType").selectpicker('val', ruleObj.purchaseType);

    $("#buyPurchaseNum").val(segment.limitEnd);
    $("#buyPurchaseUnitType").selectpicker('val', ruleObj.unit);
    if (!!ruleObj.isMultiCount && 'y' == ruleObj.isMultiCount) {
        $("#buyRecurSend").iCheck("check");
    } else {
        $("#buyRecurSend").iCheck("uncheck");
    }
};

ruleEdit.initFullSendPage = function (ruleObj) {
    $("#fullSend").iCheck("check");
    var segment = ruleObj.segments[0];
    $("#fullPurchaseType").selectpicker('val', ruleObj.purchaseType);

    $("#fullPurchaseNum").val(segment.limitEnd);
    if (!!ruleObj.isMultiCount && 'y' == ruleObj.isMultiCount) {
        $("#fullRecurSend").iCheck("check");
    } else {
        $("#fullRecurSend").iCheck("uncheck");
    }
};

ruleEdit.operation.getRuleData = function (ruleId) {
    var returnRuleObject = {};
    var data = {
        ruleId: ruleId
    };
    if (ruleId) {
        $.ajax({
            type: "GET",
            url: "/salesPromotion/ruleObject.action",
            contentType: "application/json;charset=utf-8",
            data: data,
            dataType: "json",
            async: false,
            success: function (data) {
                if (data.result == "success") {
                    returnRuleObject = data.data;
                } else {
                    window.top.window.showModalAlert(data.msg);
                }
            },
            error: function (XMLHttpRequest, textStatus) {
                if (XMLHttpRequest.status == 500) {
                    var result = eval("(" + XMLHttpRequest.responseText + ")");
                    alert(result.errorObject.errorText);
                }
            }
        });
    }
    return returnRuleObject;
};

// 初始化店铺列表
ruleEdit.initShopList = function () {
    var _shopListData = ruleEdit.operation.getCurrentShopList();
    if (!_shopListData || _shopListData.length == 0) {
        window.top.window.showModalAlert("项目没有找到可用店铺，请关闭重试");
        return;
    }

    var _tempString = "";
    for (var i = 0, j = _shopListData.length; i < j; i++) {
        _tempString = '<option value="' + _shopListData[i].shopId + '">' + _shopListData[i].shopName + '</option>'
        $("#projectShopList").append($(_tempString));
    }
};

// 初始化页面控件的取值
ruleEdit.initCompValue = function () {
    $("#everydayset").hide();
    // 下拉控件
    $("select").selectpicker("refresh").change(function () {
        if (this.valid) {
            this.valid();
        }
    });
    // 日期区间选择控件初始化
    $('.reportrange').daterangepicker({
        ranges: {
            '明天': [moment().add('days', 1).startOf('day'), moment().add('days', 1).endOf('day')],
            '未来7天': [moment().add('days', 1).startOf('day'), moment().add('days', 7).endOf('day')],
            '未来30天': [moment().add('days', 1).startOf('day'), moment().add('days', 30).endOf('day')],
            '本月': [moment().startOf('month').startOf('day'), moment().endOf('month').endOf('day')],
            '下月': [moment().add('month', 1).startOf('month').startOf('day'), moment().add('month', 1).endOf('month').endOf('day')]
        },
        timePicker: true,
        timePickerIncrement: 1,
        timePicker12Hour: false,
        minDate: moment().startOf('day').format('YYYY-MM-DD HH:mm'),
        opens: 'right', // 日期选择框的弹出位置
        buttonClasses: ['btn btn-default'],
        applyClass: 'btn-small btn-primary blue',
        cancelClass: 'btn-small',
        format: 'YYYY-MM-DD HH:mm:ss', // 控件中from和to 显示的日期格式
        separator: ' 到 ',
        locale: {
            applyLabel: '确定',
            cancelLabel: '取消',
            fromLabel: '起始时间',
            toLabel: '结束时间',
            customRangeLabel: '自定义',
            daysOfWeek: ['日', '一', '二', '三', '四', '五', '六'],
            monthNames: ['一月', '二月', '三月', '四月', '五月', '六月', '七月', '八月', '九月', '十月', '十一月', '十二月'],
            firstDay: 1
        }
    }, ruleEdit.setdaterange);
    ruleEdit.setdaterange(); // 默认时间不设置
    // 单选复选控件
    $('input[type="checkbox"],input[type="radio"]').iCheck({
        checkboxClass: 'icheckbox_flat-red',
        radioClass: 'iradio_flat-red'
    });
    // 时间控件的取值
    $("#txtEachDayTimeStart,#txtEachDayTimeEnd").inputmask({
        regex: "^([0-1]\\d|20|21|22|23):[0-5]\\d$",
        placeholder: ''
    });

    // 文本框以及录入框的长度限制
    $("input[maxlength],textarea[maxlength]").maxlength({
        alwaysShow: false,
        threshold: 20,
        warningClass: "label label-warning",
        limitReachedClass: "label label-danger",
        separator: ' / '
    });

    $("#buyPurchaseNum").inputmask("9{1,4}", {
        greedy: false,
        placeholder: ''
    });
    $("#fullPurchaseNum").inputmask("9{1,10}[.9{0,2}]", {
        greedy: false,
        placeholder: ''
    });

    // 初始化限定商品表格
    ruleEdit.initConstrainGoodsTable();
    // 初始化赠品表格
    ruleEdit.initGiftTable();
};

ruleEdit.initConstrainGoodsTable = function (constrainGoodsList) {
    if (!ruleEdit.constrainGoodsTable) {
        ruleEdit.constrainGoodsTable = $("#constrainGoodsTable").DataTable({
            "processing": true,
            "serverSide": false,
            "dom": '<"bottom"rtflp>',
            "searching": false,
            "destroy": true,
            "scrollY": "120px",
            "scrollCollapse": true,
            "paging": false,
            "deferRender": true,
            "select": {
                items: 'row'
            },
            "columns": [{
                "data": "operation",
                "defaultContent": "<a class='delete-btn' type='button'><i class='fa fa-trash-o'></i></a>",
                "orderable": false
            }, {
                "className": "truncate-text tooltip-column-detail",
                "data": "relGoodsCode",
                "orderable": false
            }, {
                "className": "truncate-text tooltip-column-detail",
                "data": "relGoodsName",
                "orderable": false
            }, {
                "className": "truncate-text tooltip-column-detail",
                "data": "relGoodsSkuCode",
                "orderable": false
            }, {
                "className": "truncate-text tooltip-column-detail",
                "data": "relGoodsSkuName",
                "orderable": false
            }, {
                "data": "relGoodsId",
                "visible": false
            }, {
                "data": "relGoodsSkuId",
                "visible": false
            }]
        }).on('draw.dt', function () {
            $("#constrainGoodsTable").find("th.sorting_asc").removeClass("sorting_asc");
            $("#constrainGoodsTable").tooltip({
                selector: ".tooltip-column-detail",
                container: "body",
                title: function () {
                    //                    
                    if ($(this)[0].scrollWidth > $(this).outerWidth()) {
                        return $(this).text();
                    }
                }
            });
        });

        $("#constrainGoodsTable tbody").on("click", ".delete-btn", function () {
            if (ruleEdit.btnType == "viewRule") {
                return;
            }
            var row = ruleEdit.constrainGoodsTable.row($(this).parents("tr"));
            row.remove();
            ruleEdit.constrainGoodsTable.draw();
        });
    }

    if (!!constrainGoodsList && constrainGoodsList.length > 0) {
        ruleEdit.constrainGoodsTable.clear();
        ruleEdit.constrainGoodsTable.rows.add(constrainGoodsList).draw();
    }
};

ruleEdit.initGiftTable = function (giftList) {
    if (!ruleEdit.giftTable) {
        ruleEdit.giftTable = $("#giftTable")
            .DataTable(
                {
                    "processing": true,
                    "serverSide": false,
                    "dom": '<"bottom"rtflp>',
                    "searching": false,
                    "destroy": true,
                    "scrollY": "200px",
                    "scrollCollapse": false,
                    "paging": false,
                    "select": {
                        items: 'row'
                    },
                    "columns": [
                        {
                            "data": "operation",
                            "defaultContent": "<a class='edit-btn' type='button'><i class='fa fa-edit'></i></a>&nbsp;<a class='delete-btn' type='button'><i class='fa fa-trash-o'></i></a>",
                            "orderable": false
                        }, {
                            "className": "truncate-text tooltip-column-detail",
                            "data": "relGoodsCode",
                            "orderable": false
                        }, {
                            "className": "truncate-text tooltip-column-detail",
                            "data": "relGoodsName",
                            "orderable": false
                        }, {
                            "className": "truncate-text tooltip-column-detail",
                            "data": "relGoodsSkuCode",
                            "orderable": false
                        }, {
                            "className": "truncate-text tooltip-column-detail",
                            "data": "relGoodsSkuName",
                            "orderable": false
                        }, {
                            "data": "presentAmount",
                            "visible": false,
                            "className": "text-right"
                        }, {
                            "data": "defaultPresentNum",
                            "className": "text-right"
                        }, {
                            "data": "priority",
                            "visible": false,
                            "className": "text-right"
                        }, {
                            "data": "relGoodsId",
                            "visible": false
                        }, {
                            "data": "relGoodsSkuId",
                            "visible": false
                        }]
                }).on('draw.dt', function () {
                $("#giftTable").find("th.sorting_asc").removeClass("sorting_asc");
                $("#giftTable").tooltip({
                    selector: ".tooltip-column-detail",
                    container: "body",
                    title: function () {
                        //
                        if ($(this)[0].scrollWidth > $(this).outerWidth()) {
                            return $(this).text();
                        }
                    }
                });
            });
        $("#giftTable tbody").unbind("click").on("click", ".edit-btn", function () {
            if (ruleEdit.btnType == "viewRule") {
                return;
            }
            var tds = $(this).parents("tr").children();
            $.each(tds, function (i, val) {
                var jqob = $(val);
                if (i < 5 || jqob.has('button').length) {
                    return true;
                }// 跳过第1项 序号,按钮
                var txt = jqob.text();
                var put = $("<input type='text' style='width:50px;' class='text-right'>").inputmask("9{1,4}", {
                    greedy: false,
                    placeholder: ''
                });
                put.val(txt);
                jqob.html(put);
            });
            $(this).html("<i class='fa fa-save'>");
            $(this).removeClass("edit-btn");
            $(this).addClass("save-btn");
        });

        $("#giftTable tbody").on("click", ".delete-btn", function () {
            if (ruleEdit.btnType == "viewRule") {
                return;
            }
            var row = ruleEdit.giftTable.row($(this).parents("tr"));
            row.remove();
            ruleEdit.giftTable.draw();
        });

        $("#giftTable tbody").on("click", ".save-btn", function () {
            if (ruleEdit.btnType == "viewRule") {
                return;
            }
            var row = ruleEdit.giftTable.row($(this).parents("tr"));
            var rowData = row.data();
            var tds = $(this).parents("tr").children();
            var lock = true;
            $.each(tds, function (i, val) {

                var jqob = $(val);
                // 把input变为字符串
                if (!jqob.has('button').length) {
                    var txt = jqob.children("input").val();
                    if (i == 5) {
                        if (txt == "" || txt == "0") {
                            lock = false;
                            return;
                        }
                    }
                    if (!!txt) {
                        var index = ruleEdit.giftTable.cell(jqob).index().column;
                        var colName = $(ruleEdit.giftTable.column(index).header()).attr("colvalue");
                        rowData[colName] = Number(txt);
                        jqob.html(Number(txt));
                    }
                }
            });
            if (!lock) {
                window.top.window.showModalAlert("备货数不能为空或0!");
                return;
            }
            row.data(rowData);
            // 设置赠品更新Flag为已更新
            $(this).html("<i class='fa fa-edit'></i>");
            $(this).addClass("edit-btn");
            $(this).removeClass("save-btn");
        });

    }

    if (!!giftList && giftList.length > 0) {
        ruleEdit.giftTable.clear();
        ruleEdit.giftTable.rows.add(giftList).draw();
    }
};

// 初始化页面控件的事件
ruleEdit.initCompEvent = function () {
    // 全天／每天的change事件
    $("#selectEachDaySet").change(function () {
        // 全天还是每天的校验
        var eachDaySet = $("option.selectEachDaySet:selected").val();
        if ("y" == eachDaySet) {
            $("#txtEachDayTimeStart,#txtEachDayTimeEnd").removeAttr("disabled");
            $("#txtEachDayTimeStart").val("00:00");
            $("#txtEachDayTimeEnd").val("23:59");
            $("#everydayset").show();
        } else {
            $("#everydayset").hide();
            $("#txtEachDayTimeStart").val("00:00");
            $("#txtEachDayTimeEnd").val("23:59");
            $("#txtEachDayTimeStart,#txtEachDayTimeEnd").attr("disabled", true);
        }
    });

    // 买就送／满就送切换
    $('input[name="sendType"]').on("ifChanged", function () {
        var checkedOption = $("input[name='sendType']:checked").eq(0).attr("id");
        $(".sendTypeContent").hide().removeClass("hidden");
        $("#" + checkedOption + "Content").fadeIn();
        $("#" + checkedOption + "Content").find("select.purchaseType").trigger("change");
    });

    // 添加限定商品按钮
    $("#btnQuickAddConstrainGoods").unbind("click").bind("click", function () {
        ruleEdit.addConstrainGoods();
    });

    // 清空限定商品按钮
    $("#btnEmptyConstrainGoods").click(function () {
        ruleEdit.emptyTable(ruleEdit.constrainGoodsTable)
    });
    // 添加赠品按钮
    $("#btnQuickAddGift").unbind("click").bind("click", function () {
        ruleEdit.addGift();
    });
    // 清空赠品按钮
    $("#btnEmptyGift").click(function () {
        ruleEdit.emptyTable(ruleEdit.giftTable)
    });

    $("#set,#priority").on("ifClicked", function (event) {
        if ($(this).attr("id") != $(".giftSendType:checked").attr("id")) {
            if ($("#giftTable tbody").find(".save-btn").length > 0) {
                window.top.window.showModalAlert("赠品编辑状态，不能切换赠送方式");

                event.cancelBubble();
                return false;
            }
        }
    });
    // 整组赠送／按照优先级赠送时，切换“优先级”列的显示隐藏
    $('#set').on("ifChecked", function () {
        ruleEdit.giftTable.column(7).visible(false, true).draw(false);
        ruleEdit.giftTable.column(5).visible(false, true).draw(false);
    });
    $('#priority').on("ifChecked", function () {
        ruleEdit.giftTable.column(7).visible(true, true).draw(false);
        ruleEdit.giftTable.column(5).visible(true, true).draw(false);
    });

    // 选择限定商品时，隐藏显示限定商品tab页；选择任意商品时，显示限定商品tab页
    $("select.purchaseType").change(function () {
        if ($(this).val() == "constrainGoods") {
            $("#constrainGoodsTab").show();
        } else {
            $("#constrainGoodsTab").hide();
        }
    })

    var sendType = $("input[name='sendType']:checked").val();
    var returnValue = "";
    // 买就送时，取商品类型
    if ("buySend" === sendType) {
        returnValue = $("#buyPurchaseType").val() === "constrainGoods" ? 'y' : 'n';
    } else if ("fullSend" === sendType) {
        returnValue = $("#fullPurchaseType").val() === "constrainGoods" ? 'y' : 'n';
    }

    // 选择种类时，隐藏多买多送；选择件数时，显示多买多送
    $("#buyPurchaseUnitType").change(function () {
        if ($(this).val() == "piece") {
            $("#multiSendGiftLabel").fadeIn();
        } else {
            $("#multiSendGiftLabel").fadeOut();
        }
    });
};

// 赠品添加按钮
ruleEdit.addGift = function () {

    var giftSkuCode = $("#goodsSkuCodeList").val();
    if (!giftSkuCode) {
        window.top.window.showModalAlert("请输入规格商家编码");
    } else if (hasAddedSkuCode(giftSkuCode, ruleEdit.giftTable)) {
        window.top.window.showModalAlert("请勿重复添加赠品");
    } else {
        giftSkuCode = giftSkuCode.replace(/，/g, ",");
        ruleEdit.operation.getGoodsBySkuCode(giftSkuCode, ruleEdit.giftTable, "y");
    }
};

// 限制商品添加按钮
ruleEdit.addConstrainGoods = function () {

    var constrainGoodsSkuCode = $("#goodsSkuCodeList4ConstrainGoods").val();

    // 将全角的逗号转换为半角的逗号
    constrainGoodsSkuCode = constrainGoodsSkuCode.replace(/，/g, ",");
    if (!constrainGoodsSkuCode) {
        window.top.window.showModalAlert("请输入规格商家编码");
    } else if (hasAddedSkuCode(constrainGoodsSkuCode, ruleEdit.constrainGoodsTable)) {
        window.top.window.showModalAlert("请勿重复添加商品");
    } else {
        constrainGoodsSkuCode = constrainGoodsSkuCode.replace(/，/g, ",");
        ruleEdit.operation.getGoodsBySkuCode(constrainGoodsSkuCode, ruleEdit.constrainGoodsTable);
    }
};

/**
 * 判断表格中是否包含规格商家编码 如果包含——返回true； 如果不包含——返回false；
 */
var hasAddedSkuCode = function (codeListString, TableObject) {
    // 获取已有数据，并校验是否重复
    var existsCode = TableObject.column(3).data();
    var hasSkuCode = false;
    for (var i = 0, j = existsCode.length; i < j; i++) {
        if (!!existsCode[i] && codeListString.indexOf(existsCode[i]) >= 0) {
            hasSkuCode = true;
            break;
        }
    }
    return hasSkuCode;
};

// 从表格中去除重复商品

var removeDuplicatedSkuCode = function (codeListString, TableObject) {
    // 获取已有数据，并去除重复
    // var existsCode = TableObject.column(3).data();
    // var codeList = codeListString.split(",");
    //    
    // var newCodeArray = [];
    // for (var i = 0, j = codeList.length; i < j; i++) {
    // if (!!codeList[i] && existsCode.indexOf(codeList[i]) >= 0) {
    // codeListString.replace
    // }
    // }
    //    
    return codeListString;
};

// 根据规格商家编码获取商品列表
ruleEdit.operation.getGoodsBySkuCode = function (giftSkuCode, tableObj, isGift) {
    var param = {};
    param.skuCodes = encodeURI(giftSkuCode);
    if (!!isGift) {
        param.isGift = isGift;
    }
    $.ajax({
        type: "GET",
        url: "/item/getProjectSkuList4SalesPromotion.action",
        data: param,
        contentType: "application/json;charset=utf-8",
        dataType: "json",
        async: false,
        success: function (data) {
            if (data.length > 0) {
                window.top.window.showScoMessage('ok', "已添加" + data.length + "种商品");
                var appendDataList = [];

                for (var i = 0, j = data.length; i < j; i++) {
                    var appendData = {
                        "relGoodsCode": data[i].goodsCode,
                        "relGoodsName": data[i].goodsName,
                        "relGoodsSkuCode": data[i].skuCode,
                        "relGoodsSkuName": data[i].skuName,
                        "relGoodsId": data[i].goodsId,
                        "relGoodsSkuId": data[i].skuId,
                        "defaultPresentNum": 0,
                        "priority": 0,
                        "presentAmount": 0
                    }
                    appendDataList.push(appendData);
                }
                tableObj.rows.add(appendDataList).draw();
            } else {
                window.top.window.showModalAlert("未找到对应商品，请确认规格商家编码");
            }
        },
        error: function (XMLHttpRequest, textStatus) {
            if (XMLHttpRequest.status == 500) {
                var result = eval("(" + XMLHttpRequest.responseText + ")");
                alert(result.errorObject.errorText);
            }
        }
    });
};

ruleEdit.setdaterange = function (start, end) {
    if (!start && !end) {
        $('.reportrange span').html("请选择日期区间");
        $('input[name="datestart"]').val("");
        $('input[name="dateend"]').val("");
    } else {
        $('.reportrange span').html(start.format('YYYY-MM-DD HH:mm') + ' - ' + end.format('YYYY-MM-DD HH:mm'));
        $('input[name="datestart"]').val(start.format("YYYY-MM-DD HH:mm"));
        $('input[name="dateend"]').val(end.format("YYYY-MM-DD HH:mm"));
    }
};

// 获取当前项目下的可访问店铺列表
ruleEdit.operation.getCurrentShopList = function () {
    var currentShopList = {};
    $.ajax({
        type: "GET",
        url: "/shop/shopListIncloudingClosed.action",
        contentType: "application/json;charset=utf-8",
        dataType: "json",
        async: false,
        success: function (data) {
            if (data.result == "success") {
                currentShopList = data.data;
            } else {
                window.top.window.showModalAlert(data.msg);
            }
        },
        error: function (XMLHttpRequest, textStatus) {
            if (XMLHttpRequest.status == 500) {
                var result = eval("(" + XMLHttpRequest.responseText + ")");
                window.top.window.showModalAlert(result.errorObject.errorText);
            }
        }
    });
    return currentShopList;
};

ruleEdit.Rule = function (sendType) {
    this.segments = [];
    this.purchaseType = "anyGoods" || "constrainGoods"; // 商品类型：任意商品或限定商品，默认是任意商品
    this.sendType = sendType || "buySend" || "fullSend" || "SegmentSend"; // 赠送方式的可用取值：买就送、满就送、分段设置，默认是买就送
    this.isMultiCount = false && true; // 是否多买多送,默认不多买多送

    if ("buySend" === sendType) {
        this.unit = "piece" || "kind";
    } else if ("fullSend" === sendType) {
        this.unit = "coin";
    }
    this.unitCountType = "single" || "mixed"; // 按商品的件数计算时，是按照单一种类的件数计算，还是按照混合种类的件数计算，默认按照单一种类计算
    this.giftType = "setSend" || "prioritySend" || "variousSend"; // 赠品整组赠送、按照优先级赠送、按照分段中的设置赠送，默认整组赠送
};

ruleEdit.sendGiftObj = function (goodsSkuId, sendCount) {
    this.goodsSkuId = goodsSkuId;
    this.sendCount = sendCount;
};

ruleEdit.Segment = function (start, end) {
    this.limitStart = start || "0"; // 分段下限默认为0
    this.limitEnd = end || "0"; // 分段上限默认为无穷大
    this.giftList = []; // 分段中的赠品列表信息,ruleEdit.sendGiftObj对象列表
};

// 构造赠送方式对象
ruleEdit.generateSendTypeObj = function () {
    var sendType = $("input[name='sendType']:checked").val();
    var rule = null;
    var isGroupEnvolve = $("#chkIsGroupEnvolve").is(":checked") ? 'y' : 'n'; // 组合商品参与
    var giftType = $(".giftSendType:checked").val();

    if ("buySend" === sendType) {
        rule = new ruleEdit.Rule(sendType);
        rule.unit = $("#buyPurchaseUnitType").val();
        rule.isMultiCount = $("#buyRecurSend").is(":checked") ? 'y' : 'n';
        rule.purchaseType = $("#buyPurchaseType").val();
        rule.isGroupEnvolve = isGroupEnvolve;
        rule.giftType = giftType;

        var sendCountEnd = $("#buyPurchaseNum").val();
        var segment = new ruleEdit.Segment(0, sendCountEnd);
        rule.segments.push(segment);
    } else if ("fullSend" === sendType) {
        rule = new ruleEdit.Rule(sendType);
        rule.isMultiCount = $("#fullRecurSend").is(":checked") ? 'y' : 'n';
        rule.purchaseType = $("#fullPurchaseType").val();
        rule.isGroupEnvolve = isGroupEnvolve;
        rule.giftType = giftType;

        var sendCountEnd = $("#fullPurchaseNum").val();
        var segment = new ruleEdit.Segment(0, sendCountEnd);
        rule.segments.push(segment);
    } else {
        rule = null;
    }
    return rule;
}

ruleEdit.generateCaculateRules = function () {
    var sendTypeObj = ruleEdit.generateSendTypeObj();
    if (!sendTypeObj) {
        window.top.window.showModalAlert("赠送方式设置异常，请检查");
        return;
    }
    return JSON.stringify(sendTypeObj);
};

// 新增规则
ruleEdit.operation.saveRuleAdd = function (context) {
    if ($("#ruleForm").valid()) {
        if ($("#selectCountingDateType").val() === "" || !$("#dateend").val()) {
            window.top.window.showModalAlert("请正确设置促销时间");
            return;
        }
        var ruleData = {
            "ruleId": $("#ruleId").val(),
            "ruleName": $("#ruleName").val(),
            "countingDateType": $("#selectCountingDateType").val(),
            "countingDateStart": $("#datestart").val(),
            "countingDateEnd": $("#dateend").val(),
            "isEnable": $("#chkIsEnable").is(":checked") ? "y" : "a",
            "isConstrainGoodsEnable": ruleEdit.getIsConstrainGoodsEnable(),
            "isEachdaySetEnable": $("#selectEachDaySet").val(),
            "isDuplicatedIdEnable": $("#chkIsDuplicatedIdEnable").is(":checked") ? "y" : "n",
            "isOrderAmountConstrainEnable": "n",
            "eachDayTimeStart": $("#txtEachDayTimeStart").val() || "00:00",
            "eachDayTimeEnd": $("#txtEachDayTimeEnd").val() || "23:59",
            "orderAmountConstrain": $("#orderAmountConstrain").val() || "0",
            "idRange": $("#idRange").val() || "",
            "presentCaculateRule": ruleEdit.generateCaculateRules(),

            "giftEditFlag": "y",
            "shopEditFlag": "y",
            "constrainGoodsEditFlag": "y"
        };

        // 添加店铺列表
        var selectedOption = $("#projectShopList").find("option:selected");
        var shopList = $.parseJSON('[{"relShopId":"' + selectedOption.val() + '","relShopName":"' + selectedOption.text() + '"}]');
        ruleData.shopList = shopList;
        // 添加赠品列表
        var giftTableData = ruleEdit.giftTable.data();
        var giftList = [];
        for (var i = 0, j = giftTableData.length; i < j; i++) {
            giftList.push(giftTableData[i]);
        }

        ruleData.giftList = giftList;
        // 添加限定商品列表
        var constrainGoodsList = [];
        if ("y" == ruleData.isConstrainGoodsEnable) {
            var constrainGoodsTableData = ruleEdit.constrainGoodsTable.data();
            for (var i = 0, j = constrainGoodsTableData.length; i < j; i++) {
                constrainGoodsList.push(constrainGoodsTableData[i]);
            }
        }
        ruleData.constrainGoodsList = constrainGoodsList;

        if (!ruleData.ruleId) {
            ruleEdit.operation.validateSaveRule(ruleData, "addRule", context);
        } else {
            ruleEdit.operation.validateSaveRule(ruleData, "updateRule", context);
        }
    }
};

ruleEdit.getIsConstrainGoodsEnable = function () {
    var sendType = $("input[name='sendType']:checked").val();
    var returnValue = "";
    // 买就送时，取商品类型
    if ("buySend" === sendType) {
        returnValue = $("#buyPurchaseType").val() === "constrainGoods" ? 'y' : 'n';
    } else if ("fullSend" === sendType) {
        returnValue = $("#fullPurchaseType").val() === "constrainGoods" ? 'y' : 'n';
    }
    return returnValue;
};

ruleEdit.operation.validateSaveRule = function (paramData, url, context) {
    if (ruleEdit.validData(paramData)) {
        // validDuplicateRule

        // 保存规则数据前的重复校验
        $.ajax({
            type: "POST",
            url: "/salesPromotion/validDuplicateRule.action",
            data: JSON.stringify(paramData),
            contentType: "application/json;charset=utf-8",
            dataType: "json",
            async: false,
            success: function (resultData) {
                if (resultData.result == "failed") {
                    if (confirm(resultData.msg)) {
                        if (paramData.isEnable == "a") {
                            if (confirm("是否立即启用该规则", "是", "否")) {
                                paramData.isEnable = "y"
                            }
                        }

                        // 保存规则数据
                        $.ajax({
                            type: "POST",
                            url: "/salesPromotion/" + url + ".action",
                            data: JSON.stringify(paramData),
                            contentType: "application/json;charset=utf-8",
                            dataType: "json",
                            async: false,
                            success: function (data) {
                                if (data.result == "success") {
                                    window.top.window.showScoMessage('ok', data.msg);
                                    $('#ruleIframeWindow', window.top.document).find("#btnClose").click();
                                } else {
                                    window.top.window.showModalAlert(data.msg);
                                }
                            },
                            error: function (XMLHttpRequest, textStatus) {
                                if (XMLHttpRequest.status == 500) {
                                    var result = eval("(" + XMLHttpRequest.responseText + ")");
                                    window.top.window.showModalAlert(result.errorObject.errorText);
                                }
                            }
                        });
                    }
                } else {
                    // 保存规则数据
                    if (paramData.isEnable == "a") {
                        if (confirm("是否立即启用该规则", "是", "否")) {
                            paramData.isEnable = "y"
                        }
                    }

                    $.ajax({
                        type: "POST",
                        url: "/salesPromotion/" + url + ".action",
                        data: JSON.stringify(paramData),
                        contentType: "application/json;charset=utf-8",
                        dataType: "json",
                        async: false,
                        success: function (data) {
                            if (data.result == "success") {
                                window.top.window.showScoMessage('ok', data.msg);
                                $('#ruleIframeWindow', window.top.document).find("#btnClose").click();
                            } else {
                                window.top.window.showModalAlert(data.msg);
                            }
                        },
                        error: function (XMLHttpRequest, textStatus) {
                            if (XMLHttpRequest.status == 500) {
                                var result = eval("(" + XMLHttpRequest.responseText + ")");
                                window.top.window.showModalAlert(result.errorObject.errorText);
                            }
                        }
                    });
                }
            },
            error: function (XMLHttpRequest, textStatus) {
                if (XMLHttpRequest.status == 500) {
                    var result = eval("(" + XMLHttpRequest.responseText + ")");
                    window.top.window.showModalAlert(result.errorObject.errorText);
                }
            }
        });
    }
};

ruleEdit.validData = function (data) {
    // 买就送／满就送的金额设置校验：金额不能为空，且不能小于0
    var rule = $.parseJSON(data.presentCaculateRule);
    var sendType = rule.sendType;
    var segmentLimitEnd = rule.segments[0].limitEnd;
    if (!segmentLimitEnd || Number(segmentLimitEnd) <= 0) {
        if ("buySend" === sendType) {
            window.top.window.showModalAlert("买就送的数量设置不正确");
        } else if ("fullSend" === sendType) {
            window.top.window.showModalAlert("满就送的金额设置不正确");
        }
        return false;
    }
    // 限定商品相关校验
    if (data.isConstrainGoodsEnable == "y") {
        // 如果启用限定商品，则限定商品列表不能为空
        if (data.constrainGoodsList.length == 0) {
            window.top.window.showModalAlert("未添加限定商品");
            return false;
        }
    }

    // 赠品相关校验
    if (data.giftList.length == 0) {
        window.top.window.showModalAlert("未添加赠品");
        return false;
    } else {
        if (rule.giftType === "prioritySend") {
            // 校验赠品的备货数设置：备货数不能为空
            for (var i = 0, j = data.giftList.length; i < j; i++) {
                giftData = data.giftList[i];
                if (!giftData.presentAmount || Number(giftData.presentAmount) <= 0) {
                    window.top.window.showModalAlert("赠品[" + data.giftList[i].relGoodsSkuCode + "]的备货数不正确，请返回修正");
                    return false;
                } else if (!giftData.defaultPresentNum || Number(giftData.defaultPresentNum) <= 0) {
                    window.top.window.showModalAlert("赠品[" + data.giftList[i].relGoodsSkuCode + "]的赠送数不正确，请返回修正");
                    return false;
                }
            }
            // 校验赠品的优先级设置：如果按照优先级赠送，则赠送优先级设置不能为空，且不能重复
            var priorityContainer = [];
            var giftData = {};
            var isEmptyFlag = false;
            var isDuplicatedFlag = false;
            for (var i = 0, j = data.giftList.length; i < j; i++) {
                giftData = data.giftList[i];
                debugger;
                if (!giftData.priority) {
                    isEmptyFlag = true;
                    break;
                } else if ($.inArray(Number(giftData.priority), priorityContainer) >= 0) {
                    isDuplicatedFlag = true;
                    break;
                } else {
                    priorityContainer.push(giftData.priority);
                }
            }
            if (!!isDuplicatedFlag) {
                window.top.window.showModalAlert("有赠品优先级设置重复，请返回修正");
                return false;
            }

            if (!!isEmptyFlag) {
                window.top.window.showModalAlert("赠品优先级不能为0或空，请返回修正");
                return false;
            }
        } else {
            // 校验赠品的赠送数设置：赠送数不能为空
            for (var i = 0, j = data.giftList.length; i < j; i++) {
                giftData = data.giftList[i];
                if (!giftData.defaultPresentNum || Number(giftData.defaultPresentNum) <= 0) {
                    window.top.window.showModalAlert("赠品[" + data.giftList[i].relGoodsSkuCode + "]的赠送数不正确，请返回修正");
                    return false;
                }
            }
        }
    }

    return true;
};

// 清空列表
ruleEdit.emptyTable = function (tableObject) {
    if (tableObject.data().length == 0) {
        window.top.window.showModalAlert("表格没有内容");
    } else {
        window.top.window.showModalConfirm("确定清空列表吗", function () {
            tableObject.clear().draw();
        });
    }
};
// ===========公共方法==========

// 获取页面参数
function GetArgsFromHref(sHref, sArgName) {
    var args = sHref.split("?");
    var retval = "";

    if (args[0] == sHref) /* 参数为空 */
    {
        return retval;
        /* 无需做任何处理 */
    }
    var str = args[1];
    args = str.split("&");
    for (var i = 0; i < args.length; i++) {
        str = args[i];
        var arg = str.split("=");
        if (arg.length <= 1)
            continue;
        if (arg[0] == sArgName)
            retval = arg[1];
    }
    return retval;
}

function extractParam(paramName) {
    var returnString = "";
    var str = window.location.search;
    if (!!str) {
        returnString = GetArgsFromHref(str, paramName);
    }
    return returnString;
}

function showSpiner() {
    $('.spinner.demo').show();
};

function hideSpiner() {
    $('.spinner.demo').fadeOut("slow");
}
